package cn.timelost.qy.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import cn.timelost.qy.common.AjaxResult;
import cn.timelost.qy.controller.vo.FileDelVo;
import cn.timelost.qy.controller.vo.FileQueryVo;
import cn.timelost.qy.service.FileService;
import cn.timelost.qy.service.UploadService;
import cn.timelost.qy.socket.WebSocketServer;
import cn.timelost.qy.util.BCryptUtil;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.img.ImgUtil.IMAGE_TYPE_PNG;

/**
 * (FileSave)表控制层
 *
 * @author snatch-yi
 * @since 2024-08-05 15:03:47
 */
@RestController
@RequestMapping("file")
public class FileController {

    @Resource
    private FileService fileService;

    @Resource
    private UploadService uploadService;

    /**
     * 分页查询
     *
     * @param fileQueryVo 筛选条件
     * @return 查询结果
     */
    @GetMapping
    public AjaxResult queryByPage(FileQueryVo fileQueryVo) {
        return AjaxResult.success(fileService.queryByPage(fileQueryVo));
    }

    /**
     * 获取本机的ipv4地址
     */
    @GetMapping("/ipv4")
    public AjaxResult getIpv4() {
        return AjaxResult.success(uploadService.getIpv4());
    }

    @GetMapping("/qrcode")
    public void getQrCode(HttpServletResponse response) throws Exception {
        QrConfig config = new QrConfig(300, 300);
        // 设置边距，既二维码和背景之间的边距
        config.setMargin(3);
        // 设置前景色
        config.setForeColor(Color.WHITE);
        // 设置背景色
        config.setBackColor(Color.BLACK);
        // 高识别度
        config.setErrorCorrection(ErrorCorrectionLevel.H);

        QrCodeUtil.generate("http://" + uploadService.getIpv4(), config, IMAGE_TYPE_PNG, response.getOutputStream());

    }

    /**
     * 新增数据
     *
     * @param file 二进制文件对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult add(@RequestBody MultipartFile file) {
        Long id = uploadService.uploadFile(file);
        if (id != null) {
            fileService.insert(file, id);
            WebSocketServer.broadcast("有新的数据！");
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    /**
     * 删除数据
     *
     * @return 删除是否成功
     */
    @DeleteMapping
    public AjaxResult deleteByIds(FileDelVo delVo) {
        if (!BCryptUtil.checkPassword(delVo.getPassword())) {
            return AjaxResult.error("密码错误！");
        }
        List<String> snowNames = getSnowFileNames(delVo.getSnowUrls());
        if (uploadService.delFileFromDisk(snowNames)) {
            fileService.deleteBySnowNames(snowNames);
            WebSocketServer.broadcast("有数据被删除！");
            return AjaxResult.success();
        }
        return AjaxResult.error(5001, "文件从磁盘中删除失败！");
    }

    private List<String> getSnowFileNames(List<String> snowUrls) {
        return snowUrls.stream().map(FileController::getSnowFileName).collect(Collectors.toList());
    }

    private static String getSnowFileName(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

}

